var express = require('express');
var router = express.Router();
const dbconfig =require('../util/dbconfig')
const {body,validationResult} =require('express-validator')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

//注册接口
router.post('/regist',
[ body('username').notEmpty().withMessage('用户名不能为空'),
body('password').notEmpty(),
body('password2').notEmpty()], //配置验证规则
(req,res,next)=>{ //判断验证结果
  const errors =validationResult(req)
  console.log(errors);
  if(!errors.isEmpty()){
    return res.status(400).json({errors:errors.array()})
  }
  next()
}
,(req,res,next)=>{
  let {username,password,password2}= req.body
  let sql ='select  * from  login where username=?'
  let sqlArr = [username]
  let callBack = (err,data)=>{
    if(err){
      console.log(err);
    }else{
      if(data.length > 0){
        res.json({
          error:'用户名已存在'
        })
      }else{
        console.log('可以注册');
        let sql ='insert into login(username,password) values(?,?)'
        let sqlArr = [username,password]
        let callBack = (err,data)=>{
        if(err){
          console.log(err);
          res.redirect('/regist')
        }else{
          res.redirect('/login')
        }
      }
      dbconfig.sqlConnect(sql,sqlArr,callBack);
      }
    }
  }
  dbconfig.sqlConnect(sql,sqlArr,callBack);

})

//登录接口
router.post('/login',(req,res,next)=>{
  const {username,password} = req.body
  console.log({username,password});
  let sql ='select  * from  login where username=? and password = ?'
  let sqlArr = [username,password]
  let callBack = (err,data)=>{
    if(err){
      res.redirect('/login')
    }else{
      if(data.length > 0){
        //登录成功，进行session会话存储
        req.session.username = username
        res.redirect('/')
      }else{
        res.redirect('/login')
      }
    }
  }
  dbconfig.sqlConnect(sql,sqlArr,callBack);
})

//退出登录
router.get('/logout',(req,res,next)=>{
  req.session.username =null
  res.redirect('/login')
})


module.exports = router;
